package com.ustc.hewei.rpc.client.loadbalance.impl;

import com.ustc.hewei.rpc.client.loadbalance.LoadBalanceChoose;
import com.ustc.hewei.rpc.common.protocol.Service;
import javafx.util.Pair;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Random;

/**
* @description: 随机负载均衡
* @author hewei
* @date 2022/8/19 10:56
* @version 1.0
*/

public class RandomChoose implements LoadBalanceChoose {
    private final Random random;

    public RandomChoose() {
        random = new Random();
    }

    @Override
    public Service chooseService(String serviceName, List<Service> services) {
        int index = random.nextInt(services.size());
        return services.get(index);
    }

    @Override
    public Service nextService(List<Service> services, String serviceName, int offset) {
        try {
            String clientIp = InetAddress.getLocalHost().getHostAddress();
            int code = clientIp.hashCode();
            int index = (code & Integer.MAX_VALUE) % services.size() + offset;
            return services.get(index % services.size());
        } catch (UnknownHostException e) {
            throw new RuntimeException("获取下一个服务失败！", e);
        }
    }
}
